import axios from 'axios'
import loginMock from '../../mock/loginMock';
import { useNavigate } from 'react-router-dom';
import { Form, Checkbox, Input, Button, message } from 'antd';
import { useEffect, useState } from 'react';

const Login = () => {

    loginMock()
    const navigate = useNavigate()
    const [checked, setChecked] = useState(false)
    const login = (username: string, password: string) => {
        axios.post('/api/login', { username: username, password: password })
            .then(response => {
                navigate('/')
                checked && saveToken(username, password)
                message.success('Loading finished')
            })
            .catch(error => {
                message.error(error.message || 'An error occurred during login.');
            });
    }
    const onFinish = (values: any) => {
        const { username, password } = values
        login(username, password)
    };

    const onChange = (values: any) => {
        setChecked(values.target.checked)
    }
    const saveToken = (username: string, password: string) => {
        localStorage.setItem("_Token", `username:${username},password:${password}`)
    }

    useEffect(() => {
        let token = localStorage.getItem('_Token')
        if (token) {
            let parts = token.split(',')
            if (parts.length == 2) {
                let username_part = parts[0].split(':')[1]
                let password_part = parts[1].split(':')[1]
                login(username_part, password_part)
            }
        }
    }, [])



    return (
        <>
            <Form onFinish={onFinish}>
                <Form.Item label='username' name='username' rules={[{ required: true, message: 'Please input your username!' }]}>
                    <Input />
                </Form.Item>
                <Form.Item label='password' name='password' rules={[{ required: true, message: 'Please input your password!' }]}>
                    <Input />
                </Form.Item>
                <Form.Item>
                    <Checkbox onChange={onChange}>Remember me</Checkbox>
                </Form.Item>
                <Form.Item>
                    <Button type="primary" htmlType="submit" >
                        Log in
                    </Button>
                    Or <a href="">register now!</a>
                </Form.Item>
            </Form>
        </>
    );
}

export default Login;